import concurrent.futures
import multiprocessing
import time
from .TraCompress import FPTD_Kmeans
from tqdm import tqdm
import json


class ParallelCompress:
    def __init__(self, trajectory_list=[], algorithmObject=None):
        self.trajectory_list = trajectory_list
        self.algorithmObject = algorithmObject

    @staticmethod
    def simulate_time_consuming_computation(trajectory):
        if len(trajectory) <= 2:
            return trajectory
        fptd = FPTD_Kmeans(trajectory)
        compress_trajectory = fptd.run()
        return compress_trajectory

    def run(self):
        compressed_trajectories = []
        start_time = time.time()
        with concurrent.futures.ProcessPoolExecutor(
            max_workers=multiprocessing.cpu_count()
        ) as executor:
            # 使用 map 函数将轨迹列表并行处理
            results = tqdm(
                executor.map(
                   ParallelCompress.simulate_time_consuming_computation, self.trajectory_list
                ),
                total=len(self.trajectory_list),
            )
            compressed_trajectories.extend(results)
        end_time = time.time()
        print("Total execution time:", end_time - start_time, "seconds")
        return compressed_trajectories


if __name__ == "__main__":
    trajectory_json = None
    with open("./data/10_300(轨迹点过滤).json", "r", encoding="utf-8") as json_file:
        trajectory_json = json.load(json_file)
    trajectory_features = trajectory_json["features"]
    tra = list(
        map(lambda feature: feature["geometry"]["coordinates"], trajectory_features)
    )
    print(len(tra))
    parallel_compress = ParallelCompress(tra)
    compressed_trajectories = parallel_compress.run()
    # 遍历并获取结果
    # for compressed_trajectory in compressed_trajectories:
    #     print(compressed_trajectory)

    print("OK")
